import 'package:flutter/material.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
import '../animations/animation_config.dart';
import 'loading_widget.dart';
import 'skeleton_widget.dart';

/// 高级分页列表组件
/// 封装infinite_scroll_pagination，提供统一的分页体验
class AdvancedPaginatedListView<T> extends StatefulWidget {
  const AdvancedPaginatedListView({
    super.key,
    required this.itemBuilder,
    required this.pageFetch,
    this.firstPageKey = 0,
    this.pageSize = 20,
    this.separatorBuilder,
    this.emptyWidget,
    this.errorWidget,
    this.loadingWidget,
    this.padding,
    this.physics,
    this.shrinkWrap = false,
    this.reverse = false,
    this.scrollDirection = Axis.vertical,
    this.itemExtent,
    this.addAutomaticKeepAlives = true,
    this.addRepaintBoundaries = true,
    this.addSemanticIndexes = true,
    this.cacheExtent,
    this.gridDelegate,
    this.enableSkeleton = true,
    this.skeletonItemCount = 5,
    this.customSkeletonItem,
    this.onItemTap,
  });

  /// 列表项构建器
  final Widget Function(BuildContext context, T item, int index) itemBuilder;
  
  /// 分页获取数据函数
  final Future<List<T>> Function(int pageKey) pageFetch;
  
  /// 首页页码
  final int firstPageKey;
  
  /// 每页数量
  final int pageSize;
  
  /// 分割线构建器
  final Widget Function(BuildContext context, int index)? separatorBuilder;
  
  /// 空状态组件
  final Widget? emptyWidget;
  
  /// 错误状态组件
  final Widget? errorWidget;
  
  /// 加载状态组件
  final Widget? loadingWidget;
  
  /// 内边距
  final EdgeInsetsGeometry? padding;
  
  /// 滚动物理效果
  final ScrollPhysics? physics;
  
  /// 是否收缩包装
  final bool shrinkWrap;
  
  /// 是否反向
  final bool reverse;
  
  /// 滚动方向
  final Axis scrollDirection;
  
  /// 项目固定高度
  final double? itemExtent;
  
  /// 自动保活
  final bool addAutomaticKeepAlives;
  
  /// 添加重绘边界
  final bool addRepaintBoundaries;
  
  /// 添加语义索引
  final bool addSemanticIndexes;
  
  /// 缓存范围
  final double? cacheExtent;
  
  /// 网格代理（用于GridView）
  final SliverGridDelegate? gridDelegate;
  
  /// 是否启用骨架屏
  final bool enableSkeleton;
  
  /// 骨架屏数量
  final int skeletonItemCount;
  
  /// 自定义骨架屏项
  final Widget? customSkeletonItem;
  
  /// 项目点击回调
  final void Function(T item, int index)? onItemTap;

  @override
  State<AdvancedPaginatedListView<T>> createState() => _AdvancedPaginatedListViewState<T>();
}

class _AdvancedPaginatedListViewState<T> extends State<AdvancedPaginatedListView<T>> {
  late PagingController<int, T> _pagingController;

  @override
  void initState() {
    super.initState();
    _pagingController = PagingController<int, T>(
      getNextPageKey: (state) {
        // If there are no pages yet, return the first page key
        if (state.keys == null || state.keys!.isEmpty) {
          return widget.firstPageKey;
        }

        // Get the last page
        final lastPage = state.pages?.last;
        if (lastPage == null || lastPage.isEmpty) {
          return null; // No more pages
        }

        // Check if the last page is smaller than pageSize, indicating it's the last page
        if (lastPage.length < widget.pageSize) {
          return null; // No more pages
        }

        // Return the next page key
        final lastKey = state.keys!.last;
        return lastKey + 1;
      },
      fetchPage: (pageKey) async {
        return await widget.pageFetch(pageKey);
      },
    );
  }

  @override
  void dispose() {
    _pagingController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.gridDelegate != null) {
      return _buildGridView();
    }
    
    if (widget.separatorBuilder != null) {
      return _buildSeparatedListView();
    }
    
    return _buildListView();
  }

  Widget _buildListView() {
    return ValueListenableBuilder<PagingState<int, T>>(
      valueListenable: _pagingController,
      builder: (context, state, _) {
        return PagedListView<int, T>(
          state: state,
          fetchNextPage: _pagingController.fetchNextPage,
          builderDelegate: _buildPagedChildBuilderDelegate(),
          padding: widget.padding as EdgeInsets?,
          physics: widget.physics,
          shrinkWrap: widget.shrinkWrap,
          reverse: widget.reverse,
          scrollDirection: widget.scrollDirection,
          itemExtent: widget.itemExtent,
          addAutomaticKeepAlives: widget.addAutomaticKeepAlives,
          addRepaintBoundaries: widget.addRepaintBoundaries,
          addSemanticIndexes: widget.addSemanticIndexes,
          cacheExtent: widget.cacheExtent,
        );
      },
    );
  }

  Widget _buildSeparatedListView() {
    return ValueListenableBuilder<PagingState<int, T>>(
      valueListenable: _pagingController,
      builder: (context, state, _) {
        return CustomScrollView(
          scrollDirection: widget.scrollDirection,
          reverse: widget.reverse,
          physics: widget.physics,
          shrinkWrap: widget.shrinkWrap,
          cacheExtent: widget.cacheExtent,
          slivers: [
            PagedSliverList<int, T>.separated(
              state: state,
              fetchNextPage: _pagingController.fetchNextPage,
              builderDelegate: _buildPagedChildBuilderDelegate(),
              separatorBuilder: widget.separatorBuilder!,
            ),
          ],
        );
      },
    );
  }

  Widget _buildGridView() {
    return ValueListenableBuilder<PagingState<int, T>>(
      valueListenable: _pagingController,
      builder: (context, state, _) {
        return PagedGridView<int, T>(
          state: state,
          fetchNextPage: _pagingController.fetchNextPage,
          builderDelegate: _buildPagedChildBuilderDelegate(),
          gridDelegate: widget.gridDelegate!,
          padding: widget.padding as EdgeInsets?,
          physics: widget.physics,
          shrinkWrap: widget.shrinkWrap,
          reverse: widget.reverse,
          scrollDirection: widget.scrollDirection,
          addAutomaticKeepAlives: widget.addAutomaticKeepAlives,
          addRepaintBoundaries: widget.addRepaintBoundaries,
          addSemanticIndexes: widget.addSemanticIndexes,
          cacheExtent: widget.cacheExtent,
        );
      },
    );
  }

  PagedChildBuilderDelegate<T> _buildPagedChildBuilderDelegate() {
    return PagedChildBuilderDelegate<T>(
      itemBuilder: (context, item, index) {
        Widget child = widget.itemBuilder(context, item, index);
        
        if (widget.onItemTap != null) {
          child = InkWell(
            onTap: () => widget.onItemTap!(item, index),
            child: child,
          );
        }
        
        return child;
      },
      firstPageProgressIndicatorBuilder: widget.enableSkeleton 
          ? _buildSkeletonIndicator 
          : _buildLoadingIndicator,
      newPageProgressIndicatorBuilder: (context) => 
          const Padding(
            padding: EdgeInsets.all(16),
            child: Center(
              child: InlineLoading(message: '加载更多...'),
            ),
          ),
      noItemsFoundIndicatorBuilder: (context) =>
          widget.emptyWidget ?? _buildEmptyIndicator(context),
      firstPageErrorIndicatorBuilder: (context) =>
          widget.errorWidget ?? _buildErrorIndicator(context),
      newPageErrorIndicatorBuilder: (context) =>
          _buildNewPageErrorIndicator(context),
    );
  }

  Widget _buildSkeletonIndicator(BuildContext context) {
    if (widget.customSkeletonItem != null) {
      return Column(
        children: List.generate(
          widget.skeletonItemCount,
          (index) => widget.customSkeletonItem!,
        ),
      );
    }
    
    return Column(
      children: List.generate(
        widget.skeletonItemCount,
        (index) => SkeletonLayouts.listItem(),
      ),
    );
  }

  Widget _buildLoadingIndicator(BuildContext context) {
    return widget.loadingWidget ?? 
           const Center(
             child: Padding(
               padding: EdgeInsets.all(32),
               child: LoadingWidget(message: '加载中...'),
             ),
           );
  }

  Widget _buildEmptyIndicator(BuildContext context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.inbox_outlined,
              size: 64,
              color: Theme.of(context).colorScheme.onSurfaceVariant,
            ),
            const SizedBox(height: 16),
            Text(
              '暂无数据',
              style: TextStyle(
                fontSize: 18,
                color: Theme.of(context).colorScheme.onSurfaceVariant,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildErrorIndicator(BuildContext context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 64,
              color: Theme.of(context).colorScheme.error,
            ),
            const SizedBox(height: 16),
            Text(
              '加载失败',
              style: TextStyle(
                fontSize: 18,
                color: Theme.of(context).colorScheme.onSurfaceVariant,
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () => _pagingController.refresh(),
              child: const Text('重试'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildNewPageErrorIndicator(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text('加载失败'),
          const SizedBox(width: 16),
          TextButton(
            onPressed: () => _pagingController.refresh(),
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  /// 刷新列表
  void refresh() => _pagingController.refresh();
  
  /// 获取控制器
  PagingController<int, T> get controller => _pagingController;
}

/// 高级刷新组件
/// 封装easy_refresh，提供统一的刷新体验
class AdvancedRefreshWidget extends StatelessWidget {
  const AdvancedRefreshWidget({
    super.key,
    required this.child,
    this.onRefresh,
    this.onLoad,
    this.enablePullDown = true,
    this.enablePullUp = true,
    this.controller,
    this.refreshOnStart = false,
    this.resetAfterRefresh = true,
    this.refreshText = '下拉刷新',
    this.refreshReadyText = '释放刷新',
    this.refreshingText = '正在刷新...',
    this.refreshedText = '刷新完成',
    this.refreshFailedText = '刷新失败',
    this.loadText = '上拉加载',
    this.loadReadyText = '释放加载',
    this.loadingText = '正在加载...',
    this.loadedText = '加载完成',
    this.loadFailedText = '加载失败',
    this.noMoreText = '没有更多了',
  });

  final Widget child;
  final Future<void> Function()? onRefresh;
  final Future<void> Function()? onLoad;
  final bool enablePullDown;
  final bool enablePullUp;
  final EasyRefreshController? controller;
  final bool refreshOnStart;
  final bool resetAfterRefresh;
  
  final String refreshText;
  final String refreshReadyText;
  final String refreshingText;
  final String refreshedText;
  final String refreshFailedText;
  
  final String loadText;
  final String loadReadyText;
  final String loadingText;
  final String loadedText;
  final String loadFailedText;
  final String noMoreText;

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      controller: controller,
      onRefresh: enablePullDown ? onRefresh : null,
      onLoad: enablePullUp ? onLoad : null,
      refreshOnStart: refreshOnStart,
      resetAfterRefresh: resetAfterRefresh,
      header: ClassicHeader(
        dragText: refreshText,
        armedText: refreshReadyText,
        readyText: refreshReadyText,
        processingText: refreshingText,
        processedText: refreshedText,
        failedText: refreshFailedText,
        messageText: refreshingText,
        textStyle: TextStyle(
          color: Theme.of(context).colorScheme.onSurface,
        ),
        iconTheme: IconThemeData(
          color: Theme.of(context).colorScheme.primary,
        ),
      ),
      footer: ClassicFooter(
        dragText: loadText,
        armedText: loadReadyText,
        readyText: loadReadyText,
        processingText: loadingText,
        processedText: loadedText,
        failedText: loadFailedText,
        noMoreText: noMoreText,
        messageText: loadingText,
        textStyle: TextStyle(
          color: Theme.of(context).colorScheme.onSurface,
        ),
        iconTheme: IconThemeData(
          color: Theme.of(context).colorScheme.primary,
        ),
      ),
      child: child,
    );
  }
}

/// 可定位滚动列表
/// 封装scrollable_positioned_list，提供定位滚动功能
class PositionedScrollableList<T> extends StatefulWidget {
  const PositionedScrollableList({
    super.key,
    required this.items,
    required this.itemBuilder,
    this.separatorBuilder,
    this.initialScrollIndex = 0,
    this.initialAlignment = 0.0,
    this.scrollDirection = Axis.vertical,
    this.reverse = false,
    this.physics,
    this.semanticChildCount,
    this.padding,
    this.itemExtent,
    this.addAutomaticKeepAlives = true,
    this.addRepaintBoundaries = true,
    this.addSemanticIndexes = true,
    this.minCacheExtent,
    this.restorationId,
    this.scrollOffsetController,
    this.scrollOffsetListener,
    this.itemPositionsListener,
    this.shrinkWrap = false,
  });

  final List<T> items;
  final Widget Function(BuildContext context, T item, int index) itemBuilder;
  final Widget Function(BuildContext context, int index)? separatorBuilder;
  final int initialScrollIndex;
  final double initialAlignment;
  final Axis scrollDirection;
  final bool reverse;
  final ScrollPhysics? physics;
  final int? semanticChildCount;
  final EdgeInsetsGeometry? padding;
  final double? itemExtent;
  final bool addAutomaticKeepAlives;
  final bool addRepaintBoundaries;
  final bool addSemanticIndexes;
  final double? minCacheExtent;
  final String? restorationId;
  final ScrollOffsetController? scrollOffsetController;
  final ScrollOffsetListener? scrollOffsetListener;
  final ItemPositionsListener? itemPositionsListener;
  final bool shrinkWrap;

  @override
  State<PositionedScrollableList<T>> createState() => _PositionedScrollableListState<T>();
}

class _PositionedScrollableListState<T> extends State<PositionedScrollableList<T>> {
  late ItemScrollController _scrollController;
  late ItemPositionsListener _positionsListener;

  @override
  void initState() {
    super.initState();
    _scrollController = ItemScrollController();
    _positionsListener = widget.itemPositionsListener ?? ItemPositionsListener.create();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.separatorBuilder != null) {
      return ScrollablePositionedList.separated(
        itemCount: widget.items.length,
        itemBuilder: (context, index) => 
            widget.itemBuilder(context, widget.items[index], index),
        separatorBuilder: widget.separatorBuilder!,
        itemScrollController: _scrollController,
        scrollOffsetController: widget.scrollOffsetController,
        itemPositionsListener: _positionsListener,
        scrollOffsetListener: widget.scrollOffsetListener,
        initialScrollIndex: widget.initialScrollIndex,
        initialAlignment: widget.initialAlignment,
        scrollDirection: widget.scrollDirection,
        reverse: widget.reverse,
        physics: widget.physics,
        semanticChildCount: widget.semanticChildCount,
        padding: widget.padding as EdgeInsets?,
        addAutomaticKeepAlives: widget.addAutomaticKeepAlives,
        addRepaintBoundaries: widget.addRepaintBoundaries,
        addSemanticIndexes: widget.addSemanticIndexes,
        minCacheExtent: widget.minCacheExtent,
        shrinkWrap: widget.shrinkWrap,
      );
    }

    return ScrollablePositionedList.builder(
      itemCount: widget.items.length,
      itemBuilder: (context, index) => 
          widget.itemBuilder(context, widget.items[index], index),
      itemScrollController: _scrollController,
      scrollOffsetController: widget.scrollOffsetController,
      itemPositionsListener: _positionsListener,
      scrollOffsetListener: widget.scrollOffsetListener,
      initialScrollIndex: widget.initialScrollIndex,
      initialAlignment: widget.initialAlignment,
      scrollDirection: widget.scrollDirection,
      reverse: widget.reverse,
      physics: widget.physics,
      semanticChildCount: widget.semanticChildCount,
      padding: widget.padding as EdgeInsets?,
      addAutomaticKeepAlives: widget.addAutomaticKeepAlives,
      addRepaintBoundaries: widget.addRepaintBoundaries,
      addSemanticIndexes: widget.addSemanticIndexes,
      shrinkWrap: widget.shrinkWrap,
    );
  }

  /// 滚动到指定索引
  Future<void> scrollToIndex({
    required int index,
    double alignment = 0.0,
    Duration duration = AnimationConfig.medium,
    Curve curve = AnimationConfig.easeOut,
  }) {
    return _scrollController.scrollTo(
      index: index,
      alignment: alignment,
      duration: duration,
      curve: curve,
    );
  }

  /// 跳转到指定索引
  void jumpToIndex(int index, {double alignment = 0.0}) {
    _scrollController.jumpTo(index: index, alignment: alignment);
  }

  /// 获取当前可见的项目位置
  Iterable<ItemPosition> get visibleItemPositions => 
      _positionsListener.itemPositions.value;

  /// 获取滚动控制器
  ItemScrollController get scrollController => _scrollController;

  /// 获取位置监听器
  ItemPositionsListener get positionsListener => _positionsListener;
}